#!/bin/sh

set -e

_ask() {
	printf "%s: " "$1"
	read -r "$2"
}

_ask "Config filename (tun0)" NAME
NAME=${NAME:-tun0}
DIR="/etc/glorytun/$NAME"

if [ -d "$DIR" ]; then
	echo "This config already exit!"
	exit 1
fi

_ask "Server ip (enter for server conf)" HOST
if [ -z "$HOST" ]; then
	_ask "Bind to port (5000)" BIND_PORT
	BIND_PORT=${BIND_PORT:-5000}
else
	_ask "Server port (5000)" PORT
	PORT=${PORT:-5000}
fi

BIND=0.0.0.0
case "$HOST" in
	*:*) BIND=::
esac

_ask "Server key (enter to generate a new one)" KEY
if [ -z "$KEY" ]; then
	KEY=$(glorytun keygen)
	echo "Your new key: $KEY"
fi

# install files
mkdir -p "$DIR"

cat > "$DIR/env" <<EOF
DEV=gt${HOST:+c}-$NAME
HOST=$HOST
PORT=$PORT
BIND=$BIND
BIND_PORT=$BIND_PORT
OPTIONS=
EOF

( umask 077; echo "$KEY" > "$DIR/key" )

[ "$HOST" ] && cat > "$DIR/post.sh" <<'EOF'
#!/bin/sh

PREF=32765
TABLE=200

# keep the current route to HOST
SRC=$(ip route get "$HOST" | awk '/src/{getline;print $0}' RS=' ')
ip rule add from "$SRC" table main pref "$((PREF-1))" || true

# limit to 100Mbit by default
glorytun path up "$SRC" dev "$DEV" rate rx 12500000 tx 12500000

# forward everything else to the tunnel
ip rule add from all table "$TABLE" pref "$PREF" || true
EOF
[ -f "$DIR/post.sh" ] && chmod u+x "$DIR/post.sh"

# start services
_ask "Start glorytun now ? (enter to skip)" START
case "$START" in y*|Y*)
	systemctl start glorytun@"$NAME" ;;
esac
